package com.gm.wholesale.module.appUpdate;
import android.content.Context;

import androidx.annotation.Nullable;

import com.allenliu.versionchecklib.core.http.HttpRequestMethod;
import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.RequestVersionListener;
import com.gm.commonlib.util.jsonUtils.JsonUtils;
import com.gm.commonlib.util.logUtils.LogUtil;
import com.gm.commonlib.views.toast.ToastUtil;
import com.gm.wholesale.BuildConfig;
import com.gm.wholesale.util.AppUtil;
public class UpdateAppUtil {

    public static void getAppVersion(Context context){

        AllenVersionChecker
                .getInstance()
                .requestVersion()
                .setRequestMethod(HttpRequestMethod.GET)
                .setRequestUrl(BuildConfig.APK_HOST+"?time="+System.currentTimeMillis())
                .request(new RequestVersionListener() {
                    @Nullable
                    @Override
                    public UIData onRequestVersionSuccess(DownloadBuilder downloadBuilder, String result) {
                        VersionBean versionBean= JsonUtils.parse(result,VersionBean.class);
                        int currentVersionCode=AppUtil.getVersionCode(context);
                        if (versionBean!=null && currentVersionCode<versionBean.getVersionCode()){
                            updateApp(context,versionBean);
                        }
                        return null;
                    }

                    @Override
                    public void onRequestVersionFailure(String message) {
                        //可能开发或者测试环境没配置对应文件，这里不处理Not Found 错误
                        if (message!=null && message.contains("Not Found")){
                            return;
                        }
                        ToastUtil.showToast(message);
                    }
                })
                .executeMission(context);
    }

    public static void updateApp(Context context,VersionBean versionBean) {
        String downUrl=versionBean.getDownUrl()+"?time="+System.currentTimeMillis();
        LogUtil.d("downUrl: "+downUrl);
        DownloadBuilder builder=AllenVersionChecker
                .getInstance()
                .downloadOnly(UIData.create().setDownloadUrl(downUrl)
                        .setTitle("有新版本，请升级")
                        .setContent(versionBean.getUpdateContent()));
        builder.setForceRedownload(true);
        builder.setShowNotification(false);
        if (versionBean.isForceRedownload()){
            builder.setForceUpdateListener(() -> AppUtil.exitApp());
        }
        builder.executeMission(context);
    }
}
